package com.org.web.handle.wechat.controller;

import com.org.web.handle.wechat.WechatCommon;
import com.org.web.support.base.BaseController;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author devg
 * @Date 2020/3/6 11:08
 */

/** 微信授权登录: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
 *  微信公众号测试平台地址: https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
 *  接口配置信息修改:url https://www.devg.cn/shop/wechart/checkToken
 *  网页账号域名： www.devg.cn
 *
 */
@Slf4j
@RestController
@RequestMapping("/wechat")
public class WechatController extends BaseController {

  @Value("${wechat.appId}")
  private String appId;

  @Value("${wechat.redirectUri}")
  private String redirectUri;

  @Value("${wechat.scope}")
  private String scope;

  @Value("${wechat.code}")
  private String code;

  @Value("${wechat.state}")
  private String state;

  @RequestMapping(value = {"/index"})
  public ModelAndView index() {
    String url = WechatCommon.authUrl + "?appid="+appId
        + "&redirect_uri="+redirectUri
        + "&response_type=code&scope="+scope
        + "&state="+state+"#wechat_redirect";
    log.info("url:" + url);
    return modelAndView("redirect:" + url);
  }

  /**
   *   token 验证,微信公众平台会用你提供的token 然后通过加密算法 将参数传入此接口
   *   该接口用自己的token通过加密算法来验证 是否正确,这里我们自己认为是正确的
   * @param request
   * @param response
   * @throws Exception
   */
  @RequestMapping(value = "/checkToken")
  public void checkToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
    log.info("请求进来了...");
    Enumeration pNames = request.getParameterNames();
    while (pNames.hasMoreElements()) {
      String name = (String) pNames.nextElement();
      String value = request.getParameter(name);
      String message = "name =" + name + ",value =" + value;
      log.info(message);
    }
    String signature = request.getParameter("signature");/// 微信加密签名
    String timestamp = request.getParameter("timestamp");/// 时间戳
    String nonce = request.getParameter("nonce"); /// 随机数
    String echostr = request.getParameter("echostr"); // 随机字符串
    PrintWriter out = response.getWriter();
    out.print(echostr);
    out.close();
  }
}
